package com.mccree.controller;

import com.alibaba.fastjson.JSON;
import com.mccree.pojo.Department;
import com.mccree.pojo.Employee;
import com.mccree.service.DepartmentService;
import com.mccree.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@Slf4j
public class EmployeeController {
    final EmployeeService employeeService;
    final DepartmentService departmentService;

    @Autowired
    public EmployeeController(EmployeeService employeeService, DepartmentService departmentService) {
        this.employeeService = employeeService;
        this.departmentService = departmentService;
    }
    /**
     * 查询全部员工信息
     */
    @GetMapping("/queryEmpList")
    public String queryEmpList(Model model){
        List<Employee> employees = employeeService.queryEmpList();
        model.addAttribute("empList",employees);
        return "emp/list";
    }
    /**
     * 添加员工(跳转至添加页面)
     */
    @GetMapping("/addEmp")
    public String addEmp(Model model){
        List<Department> departments = departmentService.queryDeptList();
        model.addAttribute("deptList",departments);
        return "emp/add";
    }
    /**
     * 添加员工(跳转至员工列表)
     */
    @PostMapping("/addEmp")
    public String addEmp(Employee employee){
        employeeService.addEmp(employee);
        return "redirect:/queryEmpList";
    }
    /**
     * 修改员工信息(跳转至修改页面)
     */
    @GetMapping("/updateEmp/{id}")
    public String updateEmp(@PathVariable("id")Integer id,Model model){
        Employee employee = employeeService.queryEmpById(id);
        model.addAttribute("emp",employee);
        List<Department> departments = departmentService.queryDeptList();
        model.addAttribute("deptList",departments);
        return "emp/update";
    }
    /**
     * 修改员工信息(跳转至员工列表页)
     */
    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeService.updateEmpById(employee);
        return "redirect:/queryEmpList";
    }
    /**
     * 根据id删除员工信息
     */
    @GetMapping("/deleteEmp/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){
        employeeService.removeEmp(id);
        return "redirect:/queryEmpList";
    }
}
